package com.haiyi.activiti.engine.framework.template.freemarker;

import com.haiyi.activiti.engine.model.entity.FormModel;
import com.haiyi.activiti.engine.model.entity.User;
import com.haiyi.activiti.engine.framework.basic.SecurityAdapter;
import com.haiyi.activiti.engine.framework.template.StringResolverEnum;
import com.haiyi.activiti.engine.framework.template.StringResolverFactory;
import com.haiyi.activiti.engine.framework.template.object.FormObj;
import com.haiyi.activiti.engine.framework.template.object.TaskObj;
import com.haiyi.activiti.engine.framework.template.object.UserObj;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p> </p>
 *
 * <pre> Created: 2018/12/10 14:10 </pre>
 *
 * @author hlu
 * @version 1.0
 * @since JDK 1.7
 */
@Component
public class FreemarkerResolverTemplate extends AbstractFreemarkerBuilderAdapter {
    @Autowired
    private SecurityAdapter securityAdapter;
    @Autowired
    private StringResolverFactory stringResolverFactory;

    @Override
    public void buildParams(FormModel formModel, Task task, FreemarkerBuilder freemarkerBuilder) {
        buildFormObj(formModel,freemarkerBuilder);
        buildTaskObj(task,freemarkerBuilder);
        buildUserObject(freemarkerBuilder);
        buildRequest(freemarkerBuilder);
    }

    @Override
    public Map<String, Object> getParams(FreemarkerBuilder freemarkerBuilder) {
        //这是之前提交的或是流程开始的参数
        final Map<String, Object> processParams = freemarkerBuilder.getProcessParams();

        //这是本次请求的参数，这个优先级最高
        Map<String, Object> requestParams = freemarkerBuilder.getRequestParams();

        if(requestParams==null){
            requestParams = new HashMap<>();
        }

        processParams.putAll(requestParams);

        if(freemarkerBuilder.getTaskObj()!=null) {
            processParams.put("task", freemarkerBuilder.getTaskObj());
        }
        if(freemarkerBuilder.getUserObj()!=null) {
            processParams.put("user", freemarkerBuilder.getUserObj());
        }
        if(freemarkerBuilder.getFormObj()!=null) {
            processParams.put("form", freemarkerBuilder.getFormObj());
        }
        if(freemarkerBuilder.getConfiguration()!=null) {
            processParams.put("configuration", freemarkerBuilder.getConfiguration());
        }
        if(freemarkerBuilder.getRequest()!=null) {
            processParams.put("request", freemarkerBuilder.getRequest());
        }

        return processParams;
    }

    @Override
    public String resolver(FormModel formModel, Map<String, Object> params) {
        final String result = stringResolverFactory.getRequestServiceByType(StringResolverEnum.FREEMARKER.getCode())
                .resolve(formModel.getComponentDesign().getFormObj(), params);
        return result;
    }



    private void buildUserObject(FreemarkerBuilder freemarkerBuilder) {
        UserObj userObj = new UserObj();
        final User currentUser = securityAdapter.getCurrentUser();
        userObj.setId(currentUser.getIid());
        userObj.setCreateTime(currentUser.getCreateTime());
        userObj.setLoginName(currentUser.getLoginName());
        userObj.setName(currentUser.getName());
        userObj.setStatus(currentUser.getStatus());
        freemarkerBuilder.setUserObj(userObj);
    }

    private void buildTaskObj(Task task, FreemarkerBuilder freemarkerBuilder) {
        TaskObj taskObj = new TaskObj();
        taskObj.setId(task.getId());
        taskObj.setAssignee(task.getAssignee());
        taskObj.setClaimTime(task.getClaimTime());
        taskObj.setDateTime(task.getCreateTime());
        taskObj.setDesc(task.getDescription());
        taskObj.setOwner(task.getOwner());
        taskObj.setName(task.getName());
        freemarkerBuilder.setTaskObj(taskObj);
    }

    private void buildFormObj(FormModel formModel,FreemarkerBuilder freemarkerBuilder){
        FormObj formObj = new FormObj();
        formObj.setId(formModel.getIid());
        formObj.setCreater(formModel.getComponentDesign().getCreater());
        formObj.setResourceId(formModel.getFormResourceId());
        formObj.setStatus(formModel.getComponentDesign().getStatus());
        formObj.setType(formModel.getComponentDesign().getType());
        String[] subIds = new String[formModel.getComponentDesign().getSubForms()==null? 0 : formModel.getComponentDesign().getSubForms().size()];
        for (int i = 0; i < formModel.getComponentDesign().getSubForms().size(); i++) {
            subIds[i] = formModel.getComponentDesign().getSubForms().get(i).getIid();
        }

        formObj.setSubResourceIds(subIds);
        freemarkerBuilder.setFormObj(formObj);
    }

    private void buildRequest(FreemarkerBuilder freemarkerBuilder){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        freemarkerBuilder.setRequest(request);

        final Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String,Object> params = new HashMap<>(parameterMap.size());
        for (String key : parameterMap.keySet()) {
            final String[] arr = parameterMap.get(key);
            if(arr!=null&arr.length==1){
                params.put(key,arr[0]);
            }else if(arr!=null&arr.length>1){
                params.put(key,arr);
            }else{
                params.put(key,null);
            }
        }
        freemarkerBuilder.setRequestParams(params);
    }



}
